﻿import { finalize } from 'rxjs/operators';
import { Component, OnInit, Injector } from '@angular/core';
import {
    ArticleCategoryEditDto,
    ArticleCategoryServiceProxy,
    CreateOrUpdateArticleCategoryInput
} from '@shared/service-proxies/service-proxies';

import { ModalComponentBase } from '@shared/common/modal-component-base';

@Component({
    selector: 'createOrEditArticleCategoryModal',
    templateUrl: './create-or-edit-articlecategory-modal.component.html',
    styles: [],
})
export class CreateOrEditArticleCategoryModalComponent extends ModalComponentBase implements OnInit {
    articleCategoryId?: number;
    articleCategory: ArticleCategoryEditDto = new ArticleCategoryEditDto();
    saving = false;

    constructor(injector: Injector, private _articleCategoryService: ArticleCategoryServiceProxy) {
        super(injector);
    }

    ngOnInit() {
        this.init();
    }

    init(): void {
        const self = this;

        self._articleCategoryService.getArticleCategoryForEdit(self.articleCategoryId).subscribe(result => {
            self.articleCategory = result.articleCategory;
        });
    }

    save(): void {
        const input: CreateOrUpdateArticleCategoryInput = new CreateOrUpdateArticleCategoryInput();
        input.articleCategory = this.articleCategory;
        this.saving = true;
        this._articleCategoryService
            .createOrUpdateArticleCategory(input)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(() => {
                this.notify.success(this.l('SavedSuccessfully'));
                this.success();
            });
    }
}
